// -----------------------------------------------------------------------------
// This source file is part of Matrix Platform
// 	(Universal .NET Software Development Platform)
// For the latest info, see http://www.matrixplatform.com
// 
// Copyright (c) 2009-2010, Ingenious Ltd
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.IO;
using Matrix.Common.Core.Serialization;

namespace Matrix.Common.Core.Settings
{
    /// <summary>
    /// Helps with the operation of assembly settings.
    /// XmlSerialization is used, so that settings can be easily modifyable.
    /// </summary>
    [Serializable]
    public class AssemblySettings
    {
        const string DefaultSettingsFilename = "{AssemblyName}.{ClassName}.settings.xml";

        /// <summary>
        /// Constructor.
        /// </summary>
        public AssemblySettings()
        {
        }

        /// <summary>
        /// Save assembly settings to file.
        /// </summary>
        public bool Save(Assembly assembly)
        {
            string filename = GetDefaultSettingsFilename(assembly, this.GetType());

            if (SerializationHelper.SerializeXml(filename, this).IsFailure)
            {
                CoreSystemMonitor.OperationError("Failed to save platform settings to file [" + filename + "].");
                return false;
            }

            return true;
        }

        /// <summary>
        /// Load form file, or if failed, get default settings.
        /// </summary>
        public static TType LoadOrDefault<TType>(Assembly assembly)
            where TType : AssemblySettings, new()
        {
            TType result = Load<TType>(assembly);
            if (result == null)
            {
                result = new TType();
            }

            return result as TType;
        }

        /// <summary>
        /// Will try to load settings from file.
        /// </summary>
        public static TType Load<TType>(Assembly assembly)
            where TType : AssemblySettings, new()
        {
            try
            {
                using (XmlReader reader = XmlTextReader.Create(GetDefaultSettingsFilename(assembly, typeof(TType))))
                {
                    TType result;
                    if (SerializationHelper.DeSerializeXml<TType>(reader, out result).IsSuccess)
                    {
                        return result;
                    }
                }

                CoreSystemMonitor.OperationError("Failed to extract platform settings from file [" + assembly.GetName().Name + "].");
            }
            catch (Exception ex)
            {
                CoreSystemMonitor.OperationError("Failed to extract platform settings from file [" + assembly.GetName().Name + "]", ex);
            }

            return null;
        }


        /// <summary>
        /// Get the default file name for the settings file.
        /// </summary>
        /// <returns></returns>
        public static string GetDefaultSettingsFilename(Assembly assembly, Type settingsClassType)
        {
            string projectName = "Unknown";
            if (assembly != null)
            {
                projectName = assembly.GetName().Name;
            }

            string result = DefaultSettingsFilename.Replace("{AssemblyName}", projectName);
            result = result.Replace("{ClassName}", settingsClassType.Name);
            return Path.Combine(CommonHelper.StartupExecutingDirectory, result);
        }
    }
}
